#!/usr/bin/python
# vim: tabstop=4 : expandtab : shiftwidth=4
import yaml
from random import choice,randint
import thing
import color

class ItemDropper:
    def __init__(self):
        self.prefabs = None

    def lister(self):
        self.prefabs = yaml.load(open("prefabs.yml", 'r'))
        for idx,i in enumerate(self.prefabs.keys()):
            print idx+1,i

    def chooser(self, player, mob):
        ri = randint
        action_roll = ri(1,100)
        room = thing.fetch(player.location)
        # Mob drops a random prefab
        """if action_roll in xrange(1,11) and "humanoid" in mob.attrs:
            self.prefabs = yaml.load(open("prefabs.yml", 'r'))
            name = choice(self.prefabs.keys())

            item = thing.Equipable()
            item.name = self.prefabs[name].name
            item.desc = self.prefabs[name].desc
            item.bonus = self.prefabs[name].bonus
            item.slot = self.prefabs[name].slot
            item.arch = self.prefabs[name].arch
            item.moveInto(room.uid)"""
        # Mob drops additional Gil
        if action_roll in xrange(11,31): room.gil += choice([mob.gil,
                                                             mob.gil,
                                                             mob.gil,
                                                             mob.gil+1, 
                                                             mob.gil+2])
        # Player gains significantly more experience
        if action_roll == 100: 
            player.XP += mob.deathexp*2 # This is actually *3; it's in addition to base deathexp
            player.hear("Something clicks, and you feel more experienced from this fight.", 
                                                                                color.green)
            player.hear("You gained "+str( mob.deathexp*2)+" additional experience!", 
                                                                                color.green)
        # A new item is generated and dropped
        if action_roll in xrange(31,101):
            self.forge(player, mob)

    def forge(self, player, mob=None):
        item = thing.Equipable()
        lvl = player.level
        room = thing.fetch(player.location)
        slot_options =  ["mainhand","offhand","head","face",
                         "ears","fingers","neck","torso","legs",
                         "waist","feet"]
        arch_options =  ["edged","blunt","axe","ranged",
                         "piercing","throwing"]

        item.slot = choice(slot_options)
        if item.slot in ["mainhand", "offhand"]:
            item.arch = choice(arch_options)

        quality = randint(1,20)
        if quality in xrange(1,10):
            self.bonusChooser(1, lvl, item)
            item.attrs.add("low_quality")
        if quality in xrange(10,16):
            self.bonusChooser(2, lvl, item)
            item.attrs.add("average_quality")
        if quality in xrange(16,19):
            self.bonusChooser(3, lvl, item)
            item.attrs.add("good_quality")
        if quality in [19, 20]:
            self.bonusChooser(5, lvl, item)
            item.attrs.add("superior_quality")

        self.namer(item)

        item.moveInto(room.uid)

    def bonusChooser(self, quality, lvl, item):
        bonus_options = ["str", "dex", "int", "con",
                         "dodge", "accuracy", "threat",
                         "maxHP", "maxMP", "damage", "DR"]
        for i in xrange(quality):
            # It would be great to bring this down to an
            # equation to eliminate all these 'if' statements
            bonus = choice(bonus_options)
            if lvl == 1:            item.bonus[bonus] = 1
            if lvl in xrange(2,6):
                item.bonus[bonus] = randint(1, int(round(lvl/1.2)))
            if lvl in xrange(6,16):
                item.bonus[bonus] = randint(1, int(round(lvl/1.7)))
            if lvl in xrange(16,30):
                item.bonus[bonus] = randint(1, int(round(lvl/2.5)))


    def namer(self, item):
        names = {
            # Possible item name with trailing weight values
            "edged": [
                "sword3", "knife1", "katana3", "longsword4", "greatsword5",
                "broadsword4", "shortsword3", "rapier3", "machete2"],
            "blunt": [
                "mace4", "cudgel5", "club5", "staff4", "quarterstaff4"],
            "axe":   [
                "axe4", "battle axe4", "great axe6", "war axe5",
                "wood axe3"],
            "ranged":[ 
                "hunting bow3", "shortbow3", "longbow4", "composite bow3"],
            "piercing":[
                "spear5", "lance6", "pike6", "halberd7"],
            "throwing":[
                "throwing axe3", "throwing knife2", "javelin4"],
            "head":[
                "helmet3", "coif2", "hood1", "hat1","bandana1"],
            "face":[
                "mask1", "goggles1", "handkerchief1", "veil1"],
            "ears":[
                "earrings0"],
            "fingers":[
                "ring1"],
            "neck":[
                "necklace1", "chain1", "pendant1", "locket1",
                "necklace1", "amulet1"],
            "torso":[
                "tunic", "robe", "breastplate"],
            "legs":[
                "leg-greaves3", "leggings4"],
            "waist":[
                "belt2", "sash1"],
            "feet":[
                "shoes2", "boots3", "sandals2"]
            }
        if item.slot in ["mainhand", "offhand"]:
            item_data = choice(names[item.arch])
            item.name = item_data[:-1]
            item.bonus['weight'] = int(item_data[-1])
        else:
            item_data = choice(names[item.slot])
            item.name = item_data[:-1]
            item.bonus['weight'] = int(item_data[-1])

        if item.slot in ["fingers","neck","ears"]:
            item.name = choice(["silver ", "gold ", "emerald ", "sapphire ",
                                "ruby ", "ebony ", "diamond ", ""]) + item.name

        if "good_quality" in item.attrs or "superior_quality" in item.attrs:
            if max(item.bonus, key=item.bonus.get) == 'str':
                item.name = item.name+" of "+choice(["strength", "might"])
            elif max(item.bonus, key=item.bonus.get) == 'dex':
                item.name = item.name+" of "+choice(["agility", "dexterity"])
            elif max(item.bonus, key=item.bonus.get) == 'int':
                item.name = item.name+" of "+choice(["intelligence", "smarts", "cunning"])
            elif max(item.bonus, key=item.bonus.get) == 'con':
                item.name = item.name+" of "+choice(["constitution", "fortitude"])
            elif max(item.bonus, key=item.bonus.get) == 'dodge':
                item.name = item.name+" of "+choice(["dodge"])
            elif max(item.bonus, key=item.bonus.get) == 'accuracy':
                item.name = item.name+" of "+choice(["aim", "accuracy"])
            elif max(item.bonus, key=item.bonus.get) == 'threat':
                item.name = item.name+" of "+choice(["threat"])
            elif max(item.bonus, key=item.bonus.get) == 'maxHP':
                item.name = item.name+" of "+choice(["health"])
            elif max(item.bonus, key=item.bonus.get) == 'maxMP':
                item.name = item.name+" of "+choice(["focus", "mana"])
            elif max(item.bonus, key=item.bonus.get) == 'damage':
                item.name = item.name+" of "+choice(["rage", "feroctiy"])
            elif max(item.bonus, key=item.bonus.get) == 'DR':
                item.name = item.name+" of "+choice(["resistance"])

ItemDropper = ItemDropper()

WEIGHT = {}

class NameGen:
    def __init__(self):
        self.vowels = ['a','e','i','o','u','y']
        self.cons = ['b','c','d','f','g','h','j','k','l','m','n',
                     'p','r','s','t','v','w','x','z']
        self.double_cons = ['f','g','h','k','l','m','n','p','r','s','t']
        self.digraphs = ['wh','ch','th','sh','qu', 'wr','ck']
        self.name = ""
        self.characters = 0
    
    def generateName(self):
        """Generate a random name"""
        
        # Choose first letter, and capilolize
        v_or_c = choice([self.vowels, self.cons, self.cons, self.digraphs])
        starter_letters = choice(v_or_c)
        if starter_letters in self.digraphs:
            self.name = starter_letters[0].upper()+starter_letters[1]
        else: self.name = starter_letters.upper()
        # Choose quantity of characters, and build next letters off first
        self.characters = randint(4,5)
        if self.name.lower() in self.vowels:
            self.name += choice(self.cons)
            if self.name[1] in self.double_cons:
                self.name += choice(self.double_cons) +\
                             choice(self.vowels)
                if self.name[2] in self.cons:
                    self.name += choice(self.vowels) + choice(["", choice(self.vowels),
                                                                   choice(self.cons)])
            else:
                self.name += choice(self.vowels) + choice(["", 
                                                           choice(self.vowels),
                                                           choice(self.cons)])
                if self.name[1:] in self.vowels:
                    self.name += choice(self.cons)

        if self.name.lower() in self.cons:
            self.name += choice(self.vowels) + choice([choice(self.vowels),
                                                       choice(self.cons),
                                                       choice(self.cons)])
        if self.name.lower() in self.digraphs:
            self.name += choice(self.vowels) + choice([choice(self.cons),
                                                       choice(self.double_cons)])
            if self.name[3] in self.double_cons:
                self.name += choice([choice(self.vowels), choice(self.double_cons)])
                if self.name[1:] in self.cons:
                    self.name += choice(self.vowels)

        return self.name

Gen = NameGen()

if __name__ == "__main__":
    gen = NameGen()
    for x in xrange(100):
        print gen.generateName()


